﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
/// <summary>
/// normal pages with all resources, a title, and its own friendly url
/// </summary>
/// 

namespace Shut
{
	public class UiPage : System.Web.UI.Page
	{
		public int BrowserMajor;
		public string BrowserName;
		public bool isWeb = true;
		public bool isMobile = false;
		private int order = 0; // keep order of added controls to header
		public BaseUser PageUser;

		public string pageDirection;
		public bool forcePageDirection = false;
		public string pageCulture = "en";

		public bool IsHomePage = false;

        private List<IDisposable> _pageLifeSpanningDisposables = new List<IDisposable>();

        protected T GetPageLifeSpanningObject<T>() where T : class, IDisposable, new()
        {
            T service = new T();

            _pageLifeSpanningDisposables.Add(service);

            return service;
        }

        protected override void OnUnload(EventArgs e)
        {
            base.OnUnload(e);

            foreach (IDisposable disposable in _pageLifeSpanningDisposables)
            {
                if (null != disposable)
                {
                    disposable.Dispose();
                }
            }
        }

        protected override void OnError(EventArgs e)
        {
            base.OnError(e);

            foreach (IDisposable disposable in _pageLifeSpanningDisposables)
            {
                if (null != disposable)
                {
                    disposable.Dispose();
                }
            }

            //TODO: Log Error
        }

		protected override void OnPreInit(EventArgs e)
		{
			PageUser = BaseUser.LoadUser(true);

			SiteSettings.Instance.SiteDirection = BaseUser.GetUserSiteDirection(true); // get direction from cookie, set  a new cookie if not available
			SiteSettings.Instance.Localization_CultureName = BaseUser.GetUserCulture(true); // get culture from cookie, set  a new cookie if not available
			pageDirection = SiteSettings.Instance.SiteDirection;
			pageCulture = SiteSettings.Instance.Localization_CultureName;

			// define major browser
			double bversion = Convert.ToDouble(Request.Browser.Version);
			string userAgent = Request.UserAgent;
			Regex re = new Regex("\\d*");
			BrowserName = re.Replace(Request.Browser.Type, "");
			BrowserMajor = Request.Browser.MajorVersion;
		
			if (Request.Browser.IsMobileDevice || userAgent.IndexOf("iPad") > -1 || userAgent.IndexOf("mobile") > -1){
				 isMobile = true;
				 isWeb = false;
				 // TODO check other tablets
			}
			
			// get direction cookie

			base.OnPreInit(e);
			
		}
		protected override void  OnLoad(EventArgs e)
		{
			
			int _i = 0; // TODO: make a date version seeded from somewhere else

			string devlocation = ResolveUrl(SiteSettings.Instance.DevLocation);
			string csslocation = ResolveUrl(SiteSettings.Instance.CssLocation);
			string jslocation = ResolveUrl(SiteSettings.Instance.JsLocation);
			

			if (SiteSettings.Instance.DebugMode){
				Random _r = new Random();
				_i = _r.Next(100,200);

				AddStylesheetInclude(csslocation + "jquery-ui.css");
				
				AddGenericLink("text/css", "stylesheet/less", devlocation + "ui.css.aspx?d="+ pageDirection +"&" + _i, "all", "Styles");

				AddJavaScriptInclude(devlocation + "jquery-1.6.2.min.js", false, false);
				AddJavaScriptInclude(devlocation + "jquery-ui.min.js", false, false);
				
				AddJavaScriptInclude(jslocation + "ui.data.aspx?" + _i, false, false);// TODO: pass params
									 
				AddJavaScriptInclude(jslocation + "jquery.jqModal.js", false, false);
				AddJavaScriptInclude(devlocation + "less.min.js", false, false);
									 
				AddJavaScriptInclude(devlocation + "sh.0init.js?" + _i, false, false);
				AddJavaScriptInclude(devlocation + "sh.jqmodal.js?" + _i, false, false);
				AddJavaScriptInclude(devlocation + "sh.behaviors.js?" + _i, false, false);
				AddJavaScriptInclude(devlocation + "sh.AjaxPager.js?" + _i, false, false);
				AddJavaScriptInclude(devlocation + "sh.ClientTabs.js?" + _i, false, false);
				AddJavaScriptInclude(devlocation + "sh.Expandlist.js?" + _i, false, false);
				AddJavaScriptInclude(devlocation + "sh.InplaceAjax.js?" + _i, false, false);
				AddJavaScriptInclude(devlocation + "sh.SelectList.js?" + _i, false, false);
									 
				AddJavaScriptInclude(devlocation + "ui.js?" + _i, false, false);
				AddJavaScriptInclude(devlocation + "ui.dev.js?" + _i, false, false);
				
				if (isMobile)  {
					//TODO: for now this is useless, it is very much reliant on themes which i dont care about, i just want events
					//AddJavaScriptInclude(jslocation + "ui.mobile.js?" + _i, false, false);
					//AddJavaScriptInclude(devlocation + "jquery-mobile.min.js?" + _i, false, false);
				}
				
			}else{
				_i = SiteSettings.Instance.LiveVersion;
				AddStylesheetInclude(csslocation + "jquery-ui.css");
				AddStylesheetInclude(csslocation + "sh.min.css?" + _i);
				if (pageDirection == "rtl"){
					
					//AddStylesheetInclude(csslocation + "jquery-ui.rtl.css");
					AddStylesheetInclude(csslocation + "sh.rtl.min.css?" + _i);
				}
					// cdn
				AddJavaScriptInclude(SiteSettings.Instance.JqueryCDN,false,false);
				AddJavaScriptInclude(SiteSettings.Instance.JqueryUICDN, false, false);
				
				AddJavaScriptInclude(jslocation + "ui.data.aspx", false, false);// TODO: pass params

				AddJavaScriptInclude(jslocation + "jquery.jqModal.js", false, false);

				

				// shut plugins and ui.js
				AddJavaScriptInclude(jslocation + "sh.min.js?" + _i, false, false);
				AddJavaScriptInclude(jslocation + "ui.min.js?" + _i, false, false);

				if (isMobile) {
					//AddJavaScriptInclude(jslocation + "ui.mobile.js", false, false);
					//AddJavaScriptInclude(SiteSettings.Instance.JqueryMobileCDN, false, false);
				}

				// google analytics file
				AddJavaScriptInclude(jslocation + "ga.js?" + _i, false, false);
			} 

			
			// ie7 css, no need to minify
			if (BrowserName == "IE" && BrowserMajor < 8)
			{
				AddStylesheetInclude(csslocation + "ie.css");
			}

			if (BrowserName == "IE" && BrowserMajor < 9){
				AddJavaScriptInclude(jslocation + "css.respond.js", false, false);
				AddJavaScriptInclude(jslocation + "ui.html5_ie.js", false, false);
				
			}
			

			// if mobile, add view port <meta name="viewport" content="width=device-width, initial-scale=1.0,minimum-scale=1.0, maximum-scale=1.0"/>
			if (isMobile){
				AddMetaTag("viewport","width=device-width, initial-scale=1.0");
				AddMetaTag("MobileOptimized","width");
				AddMetaTag("HandheldFriendly","true");

			}
			base.OnLoad(e);
			
		}
		protected override void OnPreRenderComplete(EventArgs e)
		{
			base.OnPreRenderComplete(e);
			if (TocNode.CurrentNode.PageGroup == "admin"){
				TocNode.GetNode("Admin").Visible = true;
			}
			Page.Title = (TocNode.CurrentNode.Title + ", " + SiteSettings.Instance.SiteTitle);

		}
		public virtual void AddGenericLink(string type, string relation, string href, string media, string title)
		{
			HtmlLink link = new HtmlLink();
			link.Attributes["type"] = type;
			link.Attributes["rel"] = relation;
			link.Attributes["title"] = title;
			link.Attributes["href"] = href;
			link.Attributes["media"] = media;
			Page.Header.Controls.AddAt(order++,link);
		}
		public virtual void AddStylesheetInclude(string url, string media)
		{
			HtmlLink link = new HtmlLink();
			link.Attributes["type"] = "text/css";
			link.Attributes["href"] = url;
			link.Attributes["rel"] = "stylesheet";
			if (!string.IsNullOrEmpty(media)){
				link.Attributes["media"] = media;
			}
			//Page.Header.Controls.Add(link);
			Page.Header.Controls.AddAt(order++, link);
		}
		public virtual void AddStylesheetInclude(string url)
		{
			AddStylesheetInclude(url, null);
		}
		public virtual void AddMetaTag(string name, string value)
		{
			if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(value))
				return;

			HtmlMeta meta = new HtmlMeta();
			meta.Name = name;
			meta.Content = value;
			Page.Header.Controls.AddAt(order++, meta);
		}

		public virtual void AddJavaScriptInclude(string url, bool placeInBottom, bool addDeferAttribute)
		{
			if (placeInBottom)
			{
				string script = "<script type=\"text/javascript\"" + (addDeferAttribute ? " defer=\"defer\"" : string.Empty) + " src=\"" + url + "\"></script>";
				ClientScript.RegisterStartupScript(GetType(), url.GetHashCode().ToString(), script);

			}
			else
			{
				HtmlGenericControl script = new HtmlGenericControl("script");
				script.Attributes["type"] = "text/javascript";
				script.Attributes["src"] = url;
				if (addDeferAttribute)
				{
					script.Attributes["defer"] = "defer";
				}

				Page.Header.Controls.AddAt(order++, script);
			}
		}
	}
}